package cn.lg.soar.system.biz.modules.tenant.service.impl;

import cn.lg.soar.common.util.AssertUtil;
import cn.lg.soar.system.biz.modules.tenant.entity.TenantGrantMenu;
import cn.lg.soar.system.biz.modules.tenant.mapper.TenantGrantMenuMapper;
import cn.lg.soar.system.biz.modules.tenant.service.ITenantGrantMenuService;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * TenantMenu服务层实现
 * 租户用户
 * @author luguoxiang
 * @since 2022-04-30
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
public class TenantGrantMenuServiceImpl extends ServiceImpl<TenantGrantMenuMapper, TenantGrantMenu> implements ITenantGrantMenuService {

    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public void setMenuIds(Integer tenantId, List<Long> menuIds) {
        // 清空旧值
        clearByTenant(tenantId);
        // 批量保存新值
        if (CollectionUtils.isEmpty(menuIds)) {
            return;
        }
        // 转换
        List<TenantGrantMenu> collect = menuIds.stream()
                .distinct()
                .map(x -> {
                    TenantGrantMenu data = new TenantGrantMenu();
                    data.setMenuId(x);
                    data.setTntId(tenantId);
                    return data;
                })
                .collect(Collectors.toList());
        AssertUtil.isTrue(saveBatch(collect), "保存角色菜单失败");
    }

    @Override
    public List<Long> getMenuIds(Integer tenantId) {
        return listObjs(
                Wrappers.<TenantGrantMenu>lambdaQuery()
                        .select(TenantGrantMenu::getMenuId)
                        .eq(TenantGrantMenu::getTntId, tenantId),
                x -> Long.parseLong(x.toString())
        );
    }

    public void clearByTenant(Integer tenantId) {
        this.remove(Wrappers.<TenantGrantMenu>lambdaQuery().eq(TenantGrantMenu::getTntId, tenantId));
    }

}
